/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3ds.
 *
 * e3ds is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3ds is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3ds. If not, see <https://www.gnu.org/licenses/>.
 */

package rbmap

import "cmp"

type Iterator[K cmp.Ordered, V any] struct {
	m    *RBMap[K, V]
	n    *node[K, V]
	prev *Iterator[K, V]
	next *Iterator[K, V]

	key K
	ctx V
}

func (ts *Iterator[K, V]) Next() (*Iterator[K, V], error) {
	if ts.m == nil {
		return nil, ErrorInvalid
	}
	if ts.next == nil {
		return ts, nil
	}
	return ts.next, nil
}

func (ts *Iterator[K, V]) Prev() (*Iterator[K, V], error) {
	if ts.m == nil {
		return nil, ErrorInvalid
	}
	if ts.prev.n == nil {
		return ts, nil
	}
	return ts.prev, nil
}

func (ts *Iterator[K, V]) Key() (K, error) {
	if ts.m == nil {
		return ts.key, ErrorInvalid
	}
	if ts == ts.m.endIter {
		return ts.key, ErrorEndIter
	}
	return ts.key, nil
}

func (ts *Iterator[K, V]) Value() (V, error) {
	if ts.m == nil {
		return ts.ctx, ErrorInvalid
	}
	if ts == ts.m.endIter {
		return ts.ctx, ErrorEndIter
	}
	return ts.ctx, nil
}

func (ts *Iterator[K, V]) SetValue(val V) error {
	if ts.m == nil {
		return ErrorInvalid
	}
	if ts == ts.m.endIter {
		return ErrorEndIter
	}
	ts.ctx = val
	return nil
}

func (ts *Iterator[K, V]) Delete() (*Iterator[K, V], error) {
	next, err := ts.Next()
	if err != nil {
		return nil, err
	}
	if ts.m.deleteNode(ts.n) {
		return ts, nil
	} else {
		return next, nil
	}
}

func (ts *Iterator[K, V]) NextNoError() (out *Iterator[K, V]) {
	if ts.m == nil {
		return
	}
	if ts.next == nil {
		return
	}
	return ts.next
}

func (ts *Iterator[K, V]) PrevNoError() (out *Iterator[K, V]) {
	if ts.m == nil {
		return nil
	}
	if ts.prev.n == nil {
		return ts
	}
	return ts.prev
}

func (ts *Iterator[K, V]) KeyNoError() (out K) {
	if ts.m == nil {
		return
	}
	if ts == ts.m.endIter {
		return
	}
	return ts.key
}

func (ts *Iterator[K, V]) ValueNoError() (out V) {
	if ts.m == nil {
		return
	}
	if ts == ts.m.endIter {
		return
	}
	return ts.ctx
}
